package com_github_lib_base.ext

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.graphics.drawable.Drawable
import com.shudong.lib_base.ext.appContext
import com_github_lib_base.bean.FavoriteApp
import com_github_lib_base.ext.cache.BaseCache

fun Context.getLaunchableApps(): List<FavoriteApp> {
    val packageManager = this.packageManager
    val ownPackageName = this.packageName
    val blockedPackages = BaseCache.filterAppsList

    return arrayOf(
        Intent.CATEGORY_LEANBACK_LAUNCHER,
        Intent.CATEGORY_LAUNCHER
    ).flatMap { category ->
        val intent = Intent(Intent.ACTION_MAIN).addCategory(category)
        packageManager.queryIntentActivities(intent, 0)
    }.distinctBy { it.activityInfo.packageName }
        .filter {
            val packageName = it.activityInfo.packageName
            packageName != ownPackageName &&
                    packageName !in blockedPackages
        }
        .mapNotNull { it.toApp(packageManager) }
}

fun ResolveInfo.toApp(packageManager: PackageManager): FavoriteApp? {
    val packageName = activityInfo.packageName
    val defaultIntent = packageManager.getLaunchIntentForPackage(packageName)
    val leanbackIntent = packageManager.getLeanbackLaunchIntentForPackage(packageName)

    if (defaultIntent == null && leanbackIntent == null) return null

    return FavoriteApp(
        id = "app:$packageName",
        displayName = activityInfo.loadLabel(packageManager).toString(),
        packageName = packageName,
        launchIntentUriDefault = defaultIntent?.toUri(0),
        launchIntentUriLeanback = leanbackIntent?.toUri(0),
        favoriteOrder = null
    )
}

fun FavoriteApp.launchIntent(){
    val launchIntentUri = this.launchIntentUriLeanback ?: this.launchIntentUriDefault


    if (launchIntentUri != null) {
        appContext.startActivity(Intent.parseUri(launchIntentUri, 0))
    }
}

fun FavoriteApp.createDrawable(context: Context): Drawable {
    val packageManager = context.packageManager
    val intent = Intent.parseUri(launchIntentUriLeanback ?: launchIntentUriDefault, 0)

    return try {
        packageManager.getActivityBanner(intent) ?: packageManager.getActivityIcon(intent)
    } catch (err: PackageManager.NameNotFoundException) {
        packageManager.defaultActivityIcon
    }
}

fun Drawable.isBanner(): Boolean {
    val width = this.intrinsicWidth
    val height = this.intrinsicHeight
    // 判断宽高比是否接近横屏（如大于 1.5:1）
    return width > 0 && height > 0 && width.toFloat() / height > 1.5f
}


// 获取已安装的应用 ResolveInfo 列表
 fun Context.getInstalledApps(): List<ResolveInfo> {
    val intent = Intent(Intent.ACTION_MAIN).apply {
        addCategory(Intent.CATEGORY_LAUNCHER)
    }
    return packageManager.queryIntentActivities(intent, 0)
}





fun String.getAppIconByPackage(context: Context): Drawable {
    val packageManager = context.packageManager
    return try {
        // 获取应用的启动意图
        val intent = packageManager.getLeanbackLaunchIntentForPackage(this)
            ?: packageManager.getLaunchIntentForPackage(this)
            ?: return packageManager.defaultActivityIcon

        // 优先获取横幅图标，不存在则获取活动图标
        packageManager.getActivityBanner(intent)
            ?: packageManager.getActivityIcon(intent)
            ?: packageManager.defaultActivityIcon
    } catch (e: PackageManager.NameNotFoundException) {
        packageManager.defaultActivityIcon
    }
}

fun String.getFavoriteAppByPackageName(): FavoriteApp? {
    if (this.isBlank()) return null
    val packageManager = appContext.packageManager
    return try {
        val appInfo = packageManager.getApplicationInfo(this, 0)
        val defaultIntent = packageManager.getLaunchIntentForPackage(this)
        val leanbackIntent = packageManager.getLeanbackLaunchIntentForPackage(this)

        if (defaultIntent == null && leanbackIntent == null) return null

        FavoriteApp(
            id = "app:$this",
            displayName = appInfo.loadLabel(packageManager).toString(),
            packageName = this,
            launchIntentUriDefault = defaultIntent?.toUri(0),
            launchIntentUriLeanback = leanbackIntent?.toUri(0),
            favoriteOrder = null
        )
    } catch (e: PackageManager.NameNotFoundException) {
        null
    }
}